//
//  KKConstraintMaker.m
//  Masonry
//
//  Created by Jonas Budelmann on 20/07/13.
//  Copyright (c) 2013 cloudling. All rights reserved.
//

#import "KKConstraintMaker.h"
#import "KKViewConstraint.h"
#import "KKCompositeConstraint.h"
#import "KKConstraint+Private.h"
#import "KKViewAttribute.h"
#import "View+KKAdditions.h"

@interface KKConstraintMaker () <KKConstraintDelegate>

@property (nonatomic, weak) KK_VIEW *view;
@property (nonatomic, strong) NSMutableArray *constraints;

@end

@implementation KKConstraintMaker

- (id)initWithView:(KK_VIEW *)view {
    self = [super init];
    if (!self) return nil;
    
    self.view = view;
    self.constraints = NSMutableArray.new;
    
    return self;
}

- (NSArray *)install {
    if (self.removeExisting) {
        NSArray *installedConstraints = [KKViewConstraint installedConstraintsForView:self.view];
        for (KKConstraint *constraint in installedConstraints) {
            [constraint uninstall];
        }
    }
    NSArray *constraints = self.constraints.copy;
    for (KKConstraint *constraint in constraints) {
        constraint.updateExisting = self.updateExisting;
        [constraint install];
    }
    [self.constraints removeAllObjects];
    return constraints;
}

#pragma mark - KKConstraintDelegate

- (void)constraint:(KKConstraint *)constraint shouldBeReplacedWithConstraint:(KKConstraint *)replacementConstraint {
    NSUInteger index = [self.constraints indexOfObject:constraint];
    NSAssert(index != NSNotFound, @"Could not find constraint %@", constraint);
    [self.constraints replaceObjectAtIndex:index withObject:replacementConstraint];
}

- (KKConstraint *)constraint:(KKConstraint *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute {
    KKViewAttribute *viewAttribute = [[KKViewAttribute alloc] initWithView:self.view layoutAttribute:layoutAttribute];
    KKViewConstraint *newConstraint = [[KKViewConstraint alloc] initWithFirstViewAttribute:viewAttribute];
    if ([constraint isKindOfClass:KKViewConstraint.class]) {
        //replace with composite constraint
        NSArray *children = @[constraint, newConstraint];
        KKCompositeConstraint *compositeConstraint = [[KKCompositeConstraint alloc] initWithChildren:children];
        compositeConstraint.delegate = self;
        [self constraint:constraint shouldBeReplacedWithConstraint:compositeConstraint];
        return compositeConstraint;
    }
    if (!constraint) {
        newConstraint.delegate = self;
        [self.constraints addObject:newConstraint];
    }
    return newConstraint;
}

- (KKConstraint *)addConstraintWithAttributes:(KKAttribute)attrs {
    __unused KKAttribute anyAttribute = (KKAttributeLeft | KKAttributeRight | KKAttributeTop | KKAttributeBottom | KKAttributeLeading
                                          | KKAttributeTrailing | KKAttributeWidth | KKAttributeHeight | KKAttributeCenterX
                                          | KKAttributeCenterY | KKAttributeBaseline
                                          | KKAttributeFirstBaseline | KKAttributeLastBaseline
#if TARGET_OS_IPHONE || TARGET_OS_TV
                                          | KKAttributeLeftMargin | KKAttributeRightMargin | KKAttributeTopMargin | KKAttributeBottomMargin
                                          | KKAttributeLeadingMargin | KKAttributeTrailingMargin | KKAttributeCenterXWithinMargins
                                          | KKAttributeCenterYWithinMargins
#endif
                                          );
    
    NSAssert((attrs & anyAttribute) != 0, @"You didn't pass any attribute to make.attributes(...)");
    
    NSMutableArray *attributes = [NSMutableArray array];
    
    if (attrs & KKAttributeLeft) [attributes addObject:self.view.KK_left];
    if (attrs & KKAttributeRight) [attributes addObject:self.view.KK_right];
    if (attrs & KKAttributeTop) [attributes addObject:self.view.KK_top];
    if (attrs & KKAttributeBottom) [attributes addObject:self.view.KK_bottom];
    if (attrs & KKAttributeLeading) [attributes addObject:self.view.KK_leading];
    if (attrs & KKAttributeTrailing) [attributes addObject:self.view.KK_trailing];
    if (attrs & KKAttributeWidth) [attributes addObject:self.view.KK_width];
    if (attrs & KKAttributeHeight) [attributes addObject:self.view.KK_height];
    if (attrs & KKAttributeCenterX) [attributes addObject:self.view.KK_centerX];
    if (attrs & KKAttributeCenterY) [attributes addObject:self.view.KK_centerY];
    if (attrs & KKAttributeBaseline) [attributes addObject:self.view.KK_baseline];
    if (attrs & KKAttributeFirstBaseline) [attributes addObject:self.view.KK_firstBaseline];
    if (attrs & KKAttributeLastBaseline) [attributes addObject:self.view.KK_lastBaseline];
    
#if TARGET_OS_IPHONE || TARGET_OS_TV
    
    if (attrs & KKAttributeLeftMargin) [attributes addObject:self.view.KK_leftMargin];
    if (attrs & KKAttributeRightMargin) [attributes addObject:self.view.KK_rightMargin];
    if (attrs & KKAttributeTopMargin) [attributes addObject:self.view.KK_topMargin];
    if (attrs & KKAttributeBottomMargin) [attributes addObject:self.view.KK_bottomMargin];
    if (attrs & KKAttributeLeadingMargin) [attributes addObject:self.view.KK_leadingMargin];
    if (attrs & KKAttributeTrailingMargin) [attributes addObject:self.view.KK_trailingMargin];
    if (attrs & KKAttributeCenterXWithinMargins) [attributes addObject:self.view.KK_centerXWithinMargins];
    if (attrs & KKAttributeCenterYWithinMargins) [attributes addObject:self.view.KK_centerYWithinMargins];
    
#endif
    
    NSMutableArray *children = [NSMutableArray arrayWithCapacity:attributes.count];
    
    for (KKViewAttribute *a in attributes) {
        [children addObject:[[KKViewConstraint alloc] initWithFirstViewAttribute:a]];
    }
    
    KKCompositeConstraint *constraint = [[KKCompositeConstraint alloc] initWithChildren:children];
    constraint.delegate = self;
    [self.constraints addObject:constraint];
    return constraint;
}

#pragma mark - standard Attributes

- (KKConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute {
    return [self constraint:nil addConstraintWithLayoutAttribute:layoutAttribute];
}

- (KKConstraint *)left {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeft];
}

- (KKConstraint *)top {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTop];
}

- (KKConstraint *)right {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRight];
}

- (KKConstraint *)bottom {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottom];
}

- (KKConstraint *)leading {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeading];
}

- (KKConstraint *)trailing {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailing];
}

- (KKConstraint *)width {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeWidth];
}

- (KKConstraint *)height {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeHeight];
}

- (KKConstraint *)centerX {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterX];
}

- (KKConstraint *)centerY {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterY];
}

- (KKConstraint *)baseline {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBaseline];
}

- (KKConstraint *(^)(KKAttribute))attributes {
    return ^(KKAttribute attrs){
        return [self addConstraintWithAttributes:attrs];
    };
}

- (KKConstraint *)firstBaseline {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeFirstBaseline];
}

- (KKConstraint *)lastBaseline {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLastBaseline];
}

#if TARGET_OS_IPHONE || TARGET_OS_TV

- (KKConstraint *)leftMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeftMargin];
}

- (KKConstraint *)rightMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRightMargin];
}

- (KKConstraint *)topMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTopMargin];
}

- (KKConstraint *)bottomMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottomMargin];
}

- (KKConstraint *)leadingMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeadingMargin];
}

- (KKConstraint *)trailingMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailingMargin];
}

- (KKConstraint *)centerXWithinMargins {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterXWithinMargins];
}

- (KKConstraint *)centerYWithinMargins {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterYWithinMargins];
}

#endif


#pragma mark - composite Attributes

- (KKConstraint *)edges {
    return [self addConstraintWithAttributes:KKAttributeTop | KKAttributeLeft | KKAttributeRight | KKAttributeBottom];
}

- (KKConstraint *)size {
    return [self addConstraintWithAttributes:KKAttributeWidth | KKAttributeHeight];
}

- (KKConstraint *)center {
    return [self addConstraintWithAttributes:KKAttributeCenterX | KKAttributeCenterY];
}

#pragma mark - grouping

- (KKConstraint *(^)(dispatch_block_t group))group {
    return ^id(dispatch_block_t group) {
        NSInteger previousCount = self.constraints.count;
        group();

        NSArray *children = [self.constraints subarrayWithRange:NSMakeRange(previousCount, self.constraints.count - previousCount)];
        KKCompositeConstraint *constraint = [[KKCompositeConstraint alloc] initWithChildren:children];
        constraint.delegate = self;
        return constraint;
    };
}

@end
